import {ipcMain} from 'electron';
import mysql, {Pool, Query} from 'mysql'
import ResultDTO from "../../../src/model/ResultDTO";
import MySqlConnectInfo from "../../../src/model/mysql/MySqlConnectInfo";
import './IpcIndex'

class DataSourceManager {

    /**
     * connectName名称 + 端口号
     * @private
     */
    static poolMap: Map<number, Pool> = new Map<number, Pool>();


    public static testConnection(connectInfo: MySqlConnectInfo): Promise<ResultDTO<string>> {
        let connection = mysql.createConnection({
            host: connectInfo.host,
            port: connectInfo.port,
            user: connectInfo.user,
            password: connectInfo.password,
        })
        return new Promise((resolve, reject) => {
            connection.connect( function (err) {
                let result: ResultDTO<string> = new ResultDTO<string>();
                if (err) {
                    console.error('连接失败: ' + err);
                    result = ResultDTO.fail(JSON.stringify(err))
                    result.code = -1;
                    resolve(result);
                }else{
                    console.log('连接成功，连接ID ' + connection.threadId);
                    //关闭链接
                    connection.end();
                    result.code = 1;
                    resolve(result);
                }
            });
        })

    }

    /**
     * 查询数据库
     * @param pool
     * @param queryString
     */
    public static queryDatabase(pool: Pool, queryString: string): Promise<any> {
        return new Promise((resolve, reject) => {
            pool.query(queryString, (error, results, fields) => {
                if (error) return reject(error);
                console.log("results", results, fields)
                resolve(results);
            });
        });
    }
    public static queryDataList(connectId: number, queryString: string): Promise<any> {
        let pool: Pool = DataSourceManager.poolMap.get(connectId)
        return new Promise((resolve, reject) => {
            pool.query(queryString, (error, results, fields) => {
                if (error) return reject(error);
                console.log("results", results, fields)
                resolve(results);
            });
        });
    }
    public static queryDatabaseByConnectNameByOne(connectId: number, queryString: string): Promise<any> {
        let pool: Pool = DataSourceManager.poolMap.get(connectId)
        return new Promise((resolve, reject) => {
            pool.query(queryString, (error, results, fields) => {
                if (error) return reject(error);
                console.log("results", results, fields)

                resolve(results.length != 0 ? results[0] : null);
            });
        });
    }

    static {

        // @ts-ignore
        ipcMain.handle('executeSqlByConnectName', async (event, connectName: string, sql: string) => {
            try {
                // @ts-ignore
                let pool: Pool = DataSourceManager.poolMap.get(connectName)
                return  DataSourceManager.queryDatabase(pool, sql);
            } catch (error) {
                console.error('SQL Error: ', error);
                return [];
            }
        });


    }

    public static  createPool(connectInfo: MySqlConnectInfo) {
        const pool = mysql.createPool({
            host: connectInfo.host,
            port: connectInfo.port,
            user: connectInfo.user,
            password: connectInfo.password,
        });
        DataSourceManager.poolMap.set(<number>connectInfo.id, pool);
        return pool;
    }

    public static getDataBaseList(connectId: number): Promise<any> {
        const queryString = 'SHOW DATABASES';
        let pool = DataSourceManager.poolMap.get(connectId)
        return DataSourceManager.queryDatabase(pool, queryString)
    }
    public static getDataBaseTableList(connectId: number, database: string): Promise<any> {
        const queryString = 'SHOW TABLES FROM ' + database;
        let pool = DataSourceManager.poolMap.get(connectId)
        return DataSourceManager.queryDatabase(pool, queryString)
    }

    public static closeAll(connectId: number): Promise<ResultDTO<any>> {

        return new Promise((resolve, reject) => {
            let pool = DataSourceManager.poolMap.get(connectId)
            if (pool) {
                pool.end(err => {
                    let result: ResultDTO<any> = new ResultDTO();
                    // 如果遇到错误，会在此处捕获
                    if (err) {
                        console.error('数据库连接池关闭错误:', err);
                        result.message = JSON.stringify(err);
                        resolve(result)
                        // Handle error - this is in callback of end and not an async method.
                    } else {
                        console.log('数据库连接池已关闭');
                        DataSourceManager.poolMap.delete(connectId); // 从池映射中移除
                        resolve(result)
                    }
                })
            }
        });


    }
}

// const test: MySqlConnectInfo = {
//     connectName: "test",
//     host: '192.168.192.80',
//     port: 3306,
//     user: 'root',
//     password: 'mDct5q36n5jQXF63QZ7EmqZd',
// }

// let result = DataSourceManager.createPool(test);
// console.log("链接数据库成功 main", result)

// @ts-ignore
// let pool: Pool = DataSourceManager.poolMap.get(test.connectName);
//
// // 执行SQL查询的函数
// function queryDatabase(queryString: string) {
//     return new Promise((resolve, reject) => {
//         let currentPool = DataSourceManager.poolMap.get(test.connectName);
//         if (currentPool){
//            let query: Query =  currentPool.query(queryString, (error, results) => {
//                 if (error) return reject(error);
//                 resolve(results);
//             });
//            console.log("query:", query)
//         }else{
//
//         }
//     });
// }

// 当Vue组件请求执行SQL时
// @ts-ignore
// ipcMain.handle('execute-sql', async (event, sql) => {
//     try {
//         return await queryDatabase(sql);
//     } catch (error) {
//         console.error('SQL Error: ', error);
//         return [];
//     }
// });

// 关闭数据库连接池
// ipcMain.handle('close-database-connection', () => {
//     pool.end(function (err) {
//         // 如果遇到错误，会在此处捕获
//         if (err) console.error('Database Pool Close Error:', err);
//     });
// });
//
// // 获取数据库列表
// ipcMain.handle('get-database-list', async () => {
//     const queryString = 'SHOW DATABASES';
//     try {
//         const results = await DataSourceManager.queryDatabase(pool, queryString);
//         console.log("get-database-list'", results)
//         // 返回数据库列表
//         // @ts-ignore
//         return results.map((entry) => entry.Database);
//     } catch (error) {
//         console.error('Fetch Databases Error:', error);
//         throw new Error('Unable to fetch database list');
//     }
// });


export default  DataSourceManager;